<template>
  <div class="portfolio-container">
    <div class="portfolio-header">
      <el-button type="primary" @click="showAddDialog">添加持仓</el-button>
    </div>

    <!-- 持仓列表 -->
    <el-table :data="portfolioList">
      <el-table-column prop="code" label="股票代码" min-width="130">
        <template #default="{ row }">
          <el-button
            type="info"
            icon="DocumentCopy"
            @click="handleCopy(row.code)"
          >
            {{ row.code }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="股票名称" min-width="110" />
      <el-table-column label="所属板块" width="160">
        <template #default="{ row }">
          {{ row.sector ? `${row.sector}(${row.region})` : '' }}
        </template>
      </el-table-column>
      <el-table-column label="近百日高抛低吸" min-width="100" align="center">
        <template #default="{ row }">
          <div :class="calculateDealUI(row)">{{ calculateDeal(row) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="浮动盈亏"  min-width="100" align="right">
        <template #default="{ row }">
          <span
            :class="row.price - row.costPrice >= 0 ? 'up-text' : 'down-text'"
          >
            {{ formatProfit(row) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="收益率"  min-width="80" align="center">
        <template #default="{ row }">
          <span
            :class="row.price - row.costPrice >= 0 ? 'up-text' : 'down-text'"
          >
            {{ formatProfitPercent(row) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="当前价格"
        min-width="80"
        align="center"
      />
      <el-table-column
        prop="costPrice"
        label="成本价"
        min-width="80"
        align="center"
      />
      <el-table-column
        prop="quantity"
        label="持仓数量"
        min-width="80"
        align="center"
      />
      <el-table-column label="持仓市值"  min-width="110" align="right">
        <template #default="{ row }">
          <span>
            {{ formatPrice(row.price * row.quantity) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="主力净流入"  min-width="100" align="center">
        <template #default="{ row }">
          <span :class="row.mainMoneyNet >= 0 ? 'up-text' : 'down-text'">
            {{ formatMainMoney(row.mainMoneyNet) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="量化得分"
        prop="predictionScore"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <div
            class="score-text"
            :style="{ color: getScoreColor(row.predictionScore) }"
          >
            {{ Math.round(row.predictionScore) }}分
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="110" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleOpenDetail(row)">
            详情
          </el-button>
          <el-button type="danger" link @click="deleteStock(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加持仓对话框 -->
    <el-dialog v-model="dialogVisible" title="添加持仓" width="400px">
      <el-form :model="newStock" label-width="100px">
        <el-form-item label="股票代码">
          <el-input v-model="newStock.code" placeholder="请输入股票代码" />
        </el-form-item>
        <el-form-item label="成本价">
          <el-input-number
            v-model="newStock.costPrice"
            :precision="3"
            :step="1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="持仓数量">
          <el-input-number
            v-model="newStock.quantity"
            :step="100"
            :min="100"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addStock" :loading="adding">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <DetailStock
      v-if="showDetail"
      :info="stockInfo"
      @close="handleCloseDetail"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DocumentCopy } from '@element-plus/icons-vue';
import DetailStock from '../components/DetailStock.vue';
import {
  formatPrice,
  formatMainMoney,
  getScoreColor,
  formatProfit,
  formatProfitPercent,
  calculateDealUI,
  calculateDeal,
  handleCopy
} from '../method/index.js';
import { detailStockHook } from '../commonHooks/index.js';
import { stockStore } from '@/store/stock';
const store = stockStore();

const { showDetail, stockInfo, handleOpenDetail, handleCloseDetail } =
  detailStockHook();

const dialogVisible = ref(false);
const adding = ref(false);
const portfolioList = ref([]);
let refreshTimer = null;

const newStock = ref({
  code: '',
  costPrice: 0,
  quantity: 100
});

// 显示添加对话框
const showAddDialog = () => {
  newStock.value = {
    code: '',
    costPrice: 0,
    quantity: 100
  };
  dialogVisible.value = true;
};

// 添加股票
const addStock = async () => {
  if (
    !newStock.value.code ||
    !newStock.value.costPrice ||
    !newStock.value.quantity
  ) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  adding.value = true;
  try {
    let { data } = await store.fetchStockByCodes([newStock.value.code]);

    if (data.length === 0) {
      return ElMessage.error('添加失败');
    }
    portfolioList.value.push({
      ...data[0],
      costPrice: newStock.value.costPrice,
      quantity: newStock.value.quantity
    });
    saveToLocalStorage();
    dialogVisible.value = false;
    ElMessage.success('添加成功');
  } catch (error) {
    ElMessage.error('添加失败');
  } finally {
    adding.value = false;
  }
};

// 删除股票
const deleteStock = async (stock) => {
  await ElMessageBox.confirm('确定要删除该持仓记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  portfolioList.value = portfolioList.value.filter(
    (item) => item.code !== stock.code
  );
  saveToLocalStorage();
  ElMessage.success('删除成功');
};

// 刷新股票价格
const refreshPrices = async () => {
  if (!portfolioList.value.length) return;
  try {
    let { data } = await store.fetchStockByCodes(
      portfolioList.value.map((item) => item.code)
    );
    portfolioList.value = portfolioList.value.map((item) => {
      let info = data.find((itm) => itm && itm.code === item.code);
      return {
        ...item,
        ...info,
      };
    });
    saveToLocalStorage();
  } catch (error) {
    console.error('刷新价格失败:', error);
  }
};

// 保存到本地存储
const saveToLocalStorage = () => {
  localStorage.setItem('portfolio', JSON.stringify(portfolioList.value));
};

// 从本地存储加载
const loadFromLocalStorage = () => {
  const data = localStorage.getItem('portfolio');
  if (data) {
    portfolioList.value = JSON.parse(data);
  }
};

onMounted(() => {
  loadFromLocalStorage();
  refreshPrices();
  refreshTimer = setInterval(refreshPrices, 30000);
});

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<style lang="scss" scoped>
.portfolio-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .portfolio-header {
    display: flex;
    justify-content: right;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>
